import { defineStore } from "pinia";
import { ref } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import {
  WebSocketMessageType,
  type WebSocketMessage,
  type FriendRequestData,
} from "@/types";
import wsClient from "@/utils/websocket";
import { getReceivedFriendRequests } from "@/api/contact";

export interface FriendRequestWithLoading extends FriendRequestData {
  loading?: boolean;
}

// 定义好友请求Store
export const useContactStore = defineStore("contact", () => {
  const unreadCount = ref(0);
  const friendRequests = ref<FriendRequestWithLoading[]>([]);

  // WebSocket消息处理器
  const handleFriendRequest = (
    message: WebSocketMessage<FriendRequestData>
  ) => {
    // 1. 更新未读数量
    unreadCount.value++;

    // 2. 更新请求列表
    const newRequest: FriendRequestWithLoading = {
      ...message.data,
      loading: false,
    };
    // 3.查找是否已存在该请求
    const existingIndex = friendRequests.value.findIndex(
      (req) => req.id === newRequest.id
    );
    if (existingIndex !== -1) {
      // 如果已存在，则替换
      friendRequests.value[existingIndex] = newRequest;
    } else {
      // 如果不存在，则插入到首位
      friendRequests.value.unshift(newRequest);
    }

    // 5. 显示通知
    ElNotification({
      type: "success",
      title: "新的好友请求",
      message: `收到来自 ${message.data.nickname} 的好友请求`,
      duration: 3000,
    });
  };

  // 初始化WebSocket监听
  const initWebSocket = () => {
    wsClient.addMessageHandler(
      WebSocketMessageType.FRIEND_REQ, // 添加好友请求消息处理器
      handleFriendRequest
    );
  };

  // 清理WebSocket监听
  const cleanupWebSocket = () => {
    wsClient.removeMessageHandler(
      WebSocketMessageType.FRIEND_REQ, // 移除好友请求消息处理器
      handleFriendRequest
    );
  };

  // 获取未读好友请求数量
  const fetchUnreadCount = async () => {
    try {
      const res = await getReceivedFriendRequests();
      unreadCount.value = res.data.filter(
        (request) => request.status === 0
      ).length;
    } catch (error: any) {
      console.error("获取未读好友请求数量失败:", error);
    }
  };

  // 获取好友请求列表
  const fetchFriendRequests = async () => {
    try {
      const res = await getReceivedFriendRequests();
      friendRequests.value = res.data.map((request) => ({
        ...request,
        loading: false,
      }));
    } catch (error: any) {
      ElMessage.error(error.message || "获取好友请求列表失败");
    }
  };

  // 更新请求状态
  const updateRequestStatus = (requestId: string, status: number) => {
    const request = friendRequests.value.find((req) => req.id === requestId);
    if (request) {
      request.status = status;
      if (status !== 0) {
        unreadCount.value = Math.max(0, unreadCount.value - 1);
      }
    }
  };

  return {
    unreadCount,
    friendRequests,
    initWebSocket,
    cleanupWebSocket,
    fetchUnreadCount,
    fetchFriendRequests,
    updateRequestStatus,
  };
});
